package com.smsc.headend.task.engine.handler.impl.deviceconfig;

import com.smsc.headend.module.data.enums.OperationGroup;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName SetClockObjectHandler
 * @Description TODO
 * @Author
 * @Date 2021/11/23 10:10
 */
@Slf4j
public class SetClockObjectHandler implements TaskHandler {

    @Autowired
    TaskDAO taskDAO;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData cosemData, String actionResult) throws UDISTaskHandlerException {
        log.info("{} action result {}", atomicTask.getAtomicTaskNo(), actionResult);

        OperationName operationName = OperationName.forId(atomicTask.getOperationId());
        taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), operationName.getName(), "Success", 600l, Boolean.TRUE);

        if (isSubTaskGroupLastAtomicTask(task, atomicTask)){
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "subTaskCompleted", true,600L, true);
        }

        return 1;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}", message);

        if (atomicTask.getGroupId() == OperationGroup.SetClock.getId().intValue()) {
            if (task.getIsODR()) {
                String stepOperationName = OperationName.forId(atomicTask.getOperationId()).getName();
                String result = String.format("step %s failed, [%s]", stepOperationName, message);
                taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), stepOperationName, result, 3600l, false);
            }
        }

        return -1;
    }

}
